package com.srwl.mytx.adapter;


import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ForwardDetailsActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 捐赠适配器
 * 用于 在个人主页 显示给别人看
 */
public class DonationRecordAdapter_v1 extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "DonationRecordAdapter";
    private final List<Donation> donationList;
    private final Context context;
    private boolean bol_noData;//标记是否有数据
    private boolean bol_requestError;//标记是否有数据


    public DonationRecordAdapter_v1(Context context, List<Donation> donationList) {
        this.donationList = donationList;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            return new NoDataViewHolder(LayoutInflater.from(context).inflate(R.layout.no__data__layout, parent, false));
        } else if (viewType == Constant.ITEM_TYPE_REQUEST_ERROR) {
            return new RequestErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.request_error_layout, parent, false));
        }
        return new DonationViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_donation_record_to_topic_item_v1, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        int viewType = getItemViewType(position);
        if (viewType == Constant.ITEM_TYPE_NO_DATA) {
            ((NoDataViewHolder) holder).tv_tips.setText("没有捐赠记录");
            return;
        }
        if (viewType == Constant.ITEM_TYPE_REQUEST_ERROR) {
            return;
        }
        final Donation donation = donationList.get(position);
        if (holder instanceof DonationViewHolder) {
            final DonationViewHolder viewHolder = (DonationViewHolder) holder;


            Integer type = donation.getType();
            if (type != null) {
                if (type == Constant.DONATION_TYPE_TO_PERSON) {
                    donationToPerson(donation, viewHolder);
                } else {
                    donationToTopic(donation, viewHolder, type);
                }
            } else {
                Log.e(TAG, "onBindViewHolder: 捐赠类型为空..." + JSONObject.toJSONString(donation));
            }

            viewHolder.tv_extraMessage.setText(donation.getExtra());
            viewHolder.tv_amount.setText(Utils.moneyFormat(donation.getAmount()));
            viewHolder.tv_date.setText(DateUtils.getTimestampString(donation.getCreated()));
            viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(donation.getPraiseSize()));
            if (donation.getHasPraise() != null && donation.getHasPraise()) {
                viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_red);
            } else {
                viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_gray);
            }
            viewHolder.ll_donationPraise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (donation.getHasPraise()) {
                        removeDonationPraise(donation, viewHolder);
                    } else {
                        donationPraise(donation, viewHolder);
                    }
                }
            });

        }
    }

    /**
     * 捐赠给个人
     *
     * @param donation
     * @param viewHolder
     */
    private void donationToPerson(Donation donation, DonationViewHolder viewHolder) {
        User targetUser = donation.getTargetUser();
        if (targetUser != null) {
            viewHolder.tv_topicTitle.setText(targetUser.getUsername());
            GlideLoadUtils.glideLoad(context, targetUser.getAvatar(), viewHolder.iv_topicIcon, R.drawable.tx_default_avatar_1);
            viewHolder.tv_address.setText(targetUser.getArea());
            viewHolder.iv_topicIcon.setOnClickListener(v -> toUserProfile(targetUser));
            viewHolder.tv_topicTitle.setOnClickListener(v -> toUserProfile(targetUser));
        }
        viewHolder.tv_status.setText("[个人捐赠]");
        viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
        viewHolder.tv_type.setText("[个人]");
    }

    /**
     * 捐赠给主题 （学校 行业 地区  悬赏  曝光）
     *
     * @param donation
     * @param viewHolder
     * @param type
     */
    private void donationToTopic(Donation donation, DonationViewHolder viewHolder, Integer type) {
        final Topic targetTopic = donation.getAttachTopic();
        if (targetTopic != null) {
            String iconUrl = Utils.getIconUrlScale20(targetTopic);
            GlideLoadUtils.glideLoad(context, iconUrl, viewHolder.iv_topicIcon);
            viewHolder.tv_topicTitle.setText(targetTopic.getTitle());
            viewHolder.tv_address.setText(targetTopic.getAddress());
            viewHolder.iv_topicIcon.setOnClickListener(v -> toTopicDetail(targetTopic));
            viewHolder.tv_topicTitle.setOnClickListener(v -> toTopicDetail(targetTopic));
        }

        switch (type) {
            case Constant.DONATION_TYPE_TO_REWORD:
                viewHolder.tv_type.setText("[悬赏]");
                donationTopic(donation, viewHolder);
                break;
            case Constant.DONATION_TYPE_TO_INDUSTRY:
                viewHolder.tv_type.setText("[行业]");
                donationTopic(donation, viewHolder);
                break;
            case Constant.DONATION_TYPE_TO_AREA:
                viewHolder.tv_type.setText("[地区]");
                donationTopic(donation, viewHolder);
                break;
            case Constant.DONATION_TYPE_TO_SCHOOL:
                viewHolder.tv_type.setText("[学校]");
                donationTopic(donation, viewHolder);
                break;
            case Constant.DONATION_TYPE_TO_EXPOSURE:
                viewHolder.tv_type.setText("[曝光]");
                donationTopic(donation, viewHolder);
                break;
            case Constant.DONATION_TYPE_ADVERTISEMENT://广告位捐赠
                advertisementDonation(donation, viewHolder);

                break;
        }

    }

    /**
     * 广告位结算自动生成的捐赠  不能拆回
     *
     * @param donation
     * @param viewHolder
     */
    private void advertisementDonation(Donation donation, DonationViewHolder viewHolder) {
        Integer status = donation.getStatus();
        if (status != null) {
            if (status == Constant.DONATION_STATUS_COULD_NOT_REVOKE) {
                viewHolder.tv_status.setText("[广告捐赠]");
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
            } else if (status == Constant.DONATION_STATUS_FORWARD) {
                donationHadForward(donation, viewHolder);
            }

        } else {
            Log.e(TAG, "advertisementDonation: 状态为空" + donation.toString());
        }
    }

    private void donationTopic(Donation donation, DonationViewHolder viewHolder) {
        Integer status = donation.getStatus();
        if (status != null) {

            if (status == Constant.DONATION_STATUS_COULD_REVOKE || status == Constant.DONATION_STATUS_COULD_NOT_REVOKE) {
                viewHolder.tv_status.setText("[个人捐赠]");
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
            } else if (status == Constant.DONATION_STATUS_ACTIVE_REVOKE) {
                viewHolder.tv_status.setText("[已拆回]");
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
            } else if (status == Constant.DONATION_STATUS_PASSIVE_REVOKE) {
                viewHolder.tv_status.setText("[已取消]");
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
            } else if (status == Constant.DONATION_STATUS_FORWARD) {
                donationHadForward(donation, viewHolder);
            }
            viewHolder.tv_status.setVisibility(View.VISIBLE);
        } else {
            Log.e(TAG, "donationTopic: 状态为空，，，" + donation.toString());
        }
    }

    private void donationHadForward(Donation donation, DonationViewHolder viewHolder) {
        viewHolder.tv_status.setText("[已转赠]");
        viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_black));
        //已经转捐的点击跳转到转捐详情
        viewHolder.ll_donationStatus.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) return;
            ForwardDetailsActivity.startActivity(context, donation.getfId());
        });
    }

    private void toUserProfile(User targetUser) {
        if (ClickUtil.isFastClick()) return;
        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(Constant.EXTRA_TARGET_USER_INFO, targetUser));
    }

    private void toTopicDetail(Topic targetTopic) {
        if (ClickUtil.isFastClick()) return;
        TopicDetailsActivity.startActivity(context, targetTopic.getId());
    }


    private void donationPraise(Donation donation, DonationViewHolder viewHolder) {
        Integer praiseSize = donation.getPraiseSize();
        if (praiseSize == null) {
            praiseSize = 0;
        }
        praiseSize++;
        donation.setPraiseSize(praiseSize);
        donation.setHasPraise(true);
        viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(praiseSize));
        viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_red);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .donationPraise(donation.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    private void removeDonationPraise(Donation donation, DonationViewHolder viewHolder) {
        Integer praiseSize = donation.getPraiseSize();
        if (praiseSize == null) {
            praiseSize = 1;
        }
        praiseSize--;
        donation.setPraiseSize(praiseSize);
        donation.setHasPraise(false);
        viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(praiseSize));
        viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_gray);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .removeDonationPraise(donation.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        if (bol_noData || bol_requestError) {
            return 1;
        }
        return donationList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (bol_noData) {
            return Constant.ITEM_TYPE_NO_DATA;
        } else if (bol_requestError) {
            return Constant.ITEM_TYPE_REQUEST_ERROR;
        }
        return Constant.ITEM_TYPE_NORMAL;
    }


    class DonationViewHolder extends RecyclerView.ViewHolder {


        @BindView(R.id.iv_avatar)
        ImageView iv_topicIcon;
        @BindView(R.id.tv_nick)
        TextView tv_topicTitle;
        @BindView(R.id.tv_address)
        TextView tv_address;
        @BindView(R.id.tv_amount)
        TextView tv_amount;
        @BindView(R.id.tv_date)
        TextView tv_date;
        @BindView(R.id.tv_extra_message)
        TextView tv_extraMessage;
        @BindView(R.id.tv_status)
        TextView tv_status;
        @BindView(R.id.tv_type)
        TextView tv_type;
        @BindView(R.id.ll_donation_praise)
        LinearLayout ll_donationPraise;
        @BindView(R.id.ll_donation_status)
        LinearLayout ll_donationStatus;
        @BindView(R.id.iv_donation_praise)
        ImageView iv_donationPraise;
        @BindView(R.id.tv_donation_praise_size)
        TextView tv_donationPraiseSize;


        public DonationViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }
    }

    /**
     * 显示普通视图
     * 有数据的时候调用
     */
    public void showNormalView() {
        bol_noData = false;
        bol_requestError = false;
        notifyDataSetChanged();
    }

    /**
     * 显示无数据视图
     */
    public void showNoDataView() {
        bol_noData = true;
        notifyDataSetChanged();
    }

    /**
     * 显示请求数据错误视图
     */
    public void showErrorView() {
        bol_requestError = true;
        notifyDataSetChanged();
    }


}